# 取最近的一个
from datetime import datetime

import requests

PAGE_SIZE = 1
BASE_URL = 'https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo={game_no}&provinceId=0&pageSize={page_size}&isVerify=1&pageNo=1'
def get_date_week():
    # 定义星期对应列表
    weekday_map = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"]

    today = datetime.today()
    # 使用 weekday() 结果作为索引获取中文星期
    weekday_str = weekday_map[today.weekday()]
    return {
        "date":today.strftime("%Y年%m月%d日") + " " + weekday_str
    }

def get_url(page_size, game_no):
    """生成请求URL"""
    return BASE_URL.format(page_size=page_size, game_no=game_no)


def get_result_json(game_no):
    """获取并解析JSON数据"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Referer': 'https://www.baidu.com/'  # 根据实际网站填写
        }
        url = get_url(PAGE_SIZE, game_no)  # 修复参数传递错误
        response = requests.get(url, timeout=10, headers=headers)
        response.raise_for_status()  # 抛出HTTP错误状态码

        data = response.json()
        # 检查返回结果是否存在
        if not data or 'value' not in data or not data['value']:
            raise ValueError(f"未获取到游戏{game_no}的有效数据")

        # 返回第一个结果（最近的一期）
        return data['value']['list'][0]

    except requests.exceptions.RequestException as e:
        raise ConnectionError(f"网络请求错误: {str(e)}")
    except (KeyError, IndexError) as e:
        raise ValueError(f"数据解析错误: {str(e)}")


def get_dlt_result():
    """获取大乐透结果"""
    try:
        dlt_info = get_result_json('85')
        draw_result = dlt_info.get('lotteryDrawResult').split(' ')
        return {
            'dlt_code': dlt_info.get('lotteryDrawNum'),
            'dlt_front_info': draw_result[:5],
            'dlt_back_info': draw_result[-2:] if len(draw_result) >= 2 else []
        }
    except Exception as e:
        raise ValueError(f"获取大乐透据失败: {str(e)}")


def get_pl3_result():
    """获取排列3结果"""
    try:
        pl3_info = get_result_json('35')
        return {
            'pl3_code': pl3_info.get('lotteryDrawNum'),
            'pl3_info': pl3_info.get('lotteryDrawResult', '').split(' ')
        }
    except Exception as e:
        raise ValueError(f"获取排列3数据失败: {str(e)}")

def get_pl5_result():
    """获取排列5结果"""
    try:
        pl5_info = get_result_json('350133')
        return {
            'pl5_code': pl5_info.get('lotteryDrawNum'),
            'pl5_info': pl5_info.get('lotteryDrawResult', '').split(' ')
        }
    except Exception as e:
        raise ValueError(f"获取排列5数据失败: {str(e)}")



def get_result():
    """整合所有结果"""
    # 获取当前日期
    today = datetime.datetime.today()
    return {
        **get_date_week(),
        **get_dlt_result(),
        **get_pl3_result(),
        **get_pl5_result()
    }